package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.SpecializeService;
import com.google.project.client.Service.SpecializeServiceAsync;
import com.google.project.client.Service.TaskRequireService;
import com.google.project.client.Service.TaskRequireServiceAsync;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectTaskDTO;
import com.google.project.shared.SpecializeDTO;
import com.google.project.shared.TaskRequireDTO;

public class PMTaskRequireDialog extends DialogBox {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided = true)
	CellTable<TaskRequireDTO> ctbTaskReqList = new CellTable<TaskRequireDTO>();
	@UiField
	ListBox cboSpecialize;
	@UiField
	ListBox cboExperience;
	@UiField
	TextBox txtNumEmp;
	@UiField
	Button btnDelete;
	@UiField
	Button btnSave;
	@UiField
	Button btnClose;
	@UiField
	SimplePager pager;
	@UiField
	Label lblProjectName;
	@UiField
	Label lblTaskName;
	@UiField DateBox dbFromDate;
	@UiField DateBox dbToDate;

	interface Binder extends UiBinder<Widget, PMTaskRequireDialog> {
	}

	private final TaskRequireServiceAsync taskReqSv = GWT.create(TaskRequireService.class);
	private final SpecializeServiceAsync specSv = GWT.create(SpecializeService.class);
	final MultiSelectionModel<TaskRequireDTO> selectionModel = new MultiSelectionModel<TaskRequireDTO>();

	List<TaskRequireDTO> listTaskReqDTO = new ArrayList<TaskRequireDTO>();
	ProjectTaskDTO currTask = new ProjectTaskDTO();
	ProjectDTO currProject = new ProjectDTO();

	public PMTaskRequireDialog() {
		setWidget(binder.createAndBindUi(this));
		dbFromDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbToDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
	}

	// contructor
	public PMTaskRequireDialog(ProjectTaskDTO currTask, ProjectDTO currProject) {
		initTable();
		setWidget(binder.createAndBindUi(this));
		dbFromDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbToDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		initCbSpecialize();
		initCbExperient();
		this.currProject = currProject;
		this.currTask = currTask;
		lblProjectName.setText(currProject.getProjectName());
		lblTaskName.setText(currTask.getTaskName());
		dbFromDate.setValue(new Date(currTask.getStartDate()));
		dbToDate.setValue(new Date(currTask.getDueDate()));
		if(currTask.getStatus()!=0){
			txtNumEmp.setEnabled(false);
			btnSave.setEnabled(false);
			btnDelete.setEnabled(false);
		}
		bindData();
	}
	public void bindData(){
		taskReqSv.getTaskReqByTaskId(currTask.getId(),
				new AsyncCallback<List<TaskRequireDTO>>() {

					@Override
					public void onFailure(Throwable caught) {

					}

					@Override
					public void onSuccess(List<TaskRequireDTO> result) {
						if (result != null) {
							listTaskReqDTO = result;
						}
						LoadData(listTaskReqDTO);

					}
				});
	}
	public void initCbExperient() {
		cboExperience.addItem("< 1 năm", "1");
		cboExperience.addItem("1-3 năm", "2");
		cboExperience.addItem("3-5 năm", "3");
		cboExperience.addItem("5-10 năm", "4");
		cboExperience.addItem("> 10 năm", "5");
		cboExperience.setSelectedIndex(0);
	}

	public void initCbSpecialize() {
		specSv.getSpecList(new AsyncCallback<List<SpecializeDTO>>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(List<SpecializeDTO> result) {
				for (SpecializeDTO specializeDTO : result) {
					cboSpecialize.addItem(specializeDTO.getSpecializeName(),
							specializeDTO.getId());
				}
			}
		});
		cboSpecialize.setSelectedIndex(0);
	}

	// init ctbReportTaskList
	public void initTable() {
		ctbTaskReqList.setSelectionModel(selectionModel,
				DefaultSelectionEventManager
						.<TaskRequireDTO> createCheckboxManager());
		Column<TaskRequireDTO, Boolean> checkColumn = new Column<TaskRequireDTO, Boolean>(
				new CheckboxCell(true, false)) {
			@Override
			public Boolean getValue(TaskRequireDTO object) {
				// Get the value from the selection model.
				return selectionModel.isSelected(object);
			}
		};

		TextColumn<TaskRequireDTO> indexColumn = new TextColumn<TaskRequireDTO>() {
			@Override
			public String getValue(TaskRequireDTO taskReq) {
				return taskReq.getIndex() + "";
			}
		};
		TextColumn<TaskRequireDTO> specColumn = new TextColumn<TaskRequireDTO>() {
			@Override
			public String getValue(TaskRequireDTO taskReq) {
				return taskReq.getSpecializeName();
			}
		};
		TextColumn<TaskRequireDTO> expColumn = new TextColumn<TaskRequireDTO>() {
			@Override
			public String getValue(TaskRequireDTO taskReq) {
				int exp = taskReq.getExperience();
				String result = "";
				if (exp == 1) {
					result += " < 1 năm";
				} else if (exp == 2) {
					result += "1-3 năm";
				} else if (exp == 3) {
					result += "3-5 năm";
				} else if (exp == 4) {
					result += "5-10 năm";
				} else if (exp == 5) {
					result += " > 10 năm";
				}
				return result;
			}
		};
		TextColumn<TaskRequireDTO> NumEmpColumn = new TextColumn<TaskRequireDTO>() {
			@Override
			public String getValue(TaskRequireDTO taskReq) {
				return taskReq.getNumOfEmp() + "";
			}
		};
		ctbTaskReqList.setStyleName("ttable");
		ctbTaskReqList.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
		ctbTaskReqList.setColumnWidth(checkColumn, 40, Unit.PX);
		ctbTaskReqList.addColumn(indexColumn, "STT");
		ctbTaskReqList.getColumn(ctbTaskReqList.getColumnIndex(indexColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		ctbTaskReqList.addColumn(specColumn, "Chuyên môn");
		ctbTaskReqList.addColumn(expColumn, "Kinh nghiệm");
		ctbTaskReqList.addColumn(NumEmpColumn, "Số lượng");
	}

	// load data
	protected void LoadData(List<TaskRequireDTO> taskReqList) {

		// TODO Auto-generated method stub
		ListDataProvider<TaskRequireDTO> dataProvider = new ListDataProvider<TaskRequireDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbTaskReqList);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int index = 1;
		List<TaskRequireDTO> list = dataProvider.getList();
		for (TaskRequireDTO taskReq : taskReqList) {
			taskReq.setIndex(index);
			list.add(taskReq);
			index++;
		}
		// SimplePager
		pager.setDisplay(ctbTaskReqList);
		pager.setPageSize(5);
	}

	@UiHandler("btnDelete")
	void onBtnDeleteClick(ClickEvent event) {
		Set<TaskRequireDTO> listChecked = selectionModel.getSelectedSet();
		if(listChecked.size() == 0) {
			Window.alert("Bạn chưa chọn để xóa!");
		} else {
			List<TaskRequireDTO> list = new ArrayList<TaskRequireDTO>();
			for (TaskRequireDTO taskRequireDTO : listChecked) {
				list.add(taskRequireDTO);
			}
			if (Window.confirm("Bạn có chắc chắn muốn xóa?")) {
				taskReqSv.deleteTaskReqList(list, new AsyncCallback<Void>() {
	
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Có lỗi trong quá trình xóa!");
					}
	
					@Override
					public void onSuccess(Void result) {
						Window.alert("Xóa thành công!");
						bindData();
					}
				});
			}
		}
		selectionModel.clear();
		LoadData(listTaskReqDTO);
	}

	@UiHandler("btnClose")
	void onBtnCloseClick(ClickEvent event) {
		this.hide();
	}

	public void closeDialog() {
		this.hide();
	}

	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		if(txtNumEmp.getText()==null || txtNumEmp.getText().equalsIgnoreCase("")){
			Window.alert("Chưa nhập số lượng nhân sự yêu cầu!");
		}else{
			TaskRequireDTO taskReq = new TaskRequireDTO(currProject.getProjectID(),
					currProject.getProjectName(), currTask.getId(), currTask
							.getTaskName(), Integer.parseInt(txtNumEmp.getText()
							.trim()), cboSpecialize.getValue(cboSpecialize
							.getSelectedIndex()), cboSpecialize
							.getItemText(cboSpecialize.getSelectedIndex()), Integer
							.parseInt(cboExperience.getValue(cboExperience
									.getSelectedIndex())), currTask.getStartDate(),
					currTask.getDueDate(),"", 0);
		
			taskReqSv.addTaskReq(currTask, taskReq,
					new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							Window.alert("Có lỗi xảy ra!");

						}

						@Override
						public void onSuccess(Void result) {
							Window.alert("Lưu thành công!");
							bindData();
						}
					});
			LoadData(listTaskReqDTO);
		}
		
	}
}
